package com.ruoyi.dm.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ZipUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.exception.DataRepeatException;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.biz.BizModule;
import com.ruoyi.common.utils.biz.PathUtil;
import com.ruoyi.dm.domain.NormalFileVO;
import com.ruoyi.dm.domain.RadioStationParam;
import com.ruoyi.dm.domain.po.NormalFilePO;
import com.ruoyi.dm.mapper.NoramlFileMapper;
import com.ruoyi.dm.service.INormalFileService;
import com.ruoyi.utils.TranferUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class NormalFileImpl extends ServiceImpl<NoramlFileMapper, NormalFilePO> implements INormalFileService {


    @Override
    public IPage<NormalFileVO> query(RadioStationParam queryParam) {
        LambdaQueryWrapper<NormalFilePO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.hasLength(queryParam.getFileName()),NormalFilePO::getName,queryParam.getFileName());
        queryWrapper.le(null != queryParam.getStartDate() && null != queryParam.getEndDate() ,NormalFilePO::getUploadDate,queryParam.getStartDate());
        queryWrapper.ge(null != queryParam.getStartDate() && null != queryParam.getEndDate() ,NormalFilePO::getUploadDate,queryParam.getEndDate());
        queryWrapper.orderByAsc(NormalFilePO::getUploadDate);
        IPage page = page(queryParam.page(), queryWrapper);
        List<NormalFileVO> objects = new ArrayList<>();
        for (Object airCollectRecordPO : page.getRecords()) {
            NormalFilePO po = (NormalFilePO) airCollectRecordPO;
            NormalFileVO vo = TranferUtils.tranferNormalFilePO(po);
            objects.add(vo);
        }
        page.setRecords(objects);
        return page;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<String> input(MultipartFile[] files, String dataType) throws DataRepeatException {

        if (null != files && files.length==1) {
            String filename = files[0].getOriginalFilename();
            LambdaQueryWrapper<NormalFilePO> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(NormalFilePO::getName,filename);
            long count = count(queryWrapper);
            if (count >0) {
                throw new DataRepeatException();
            }
        }
        Date now = new Date();
        List<NormalFilePO> list = new ArrayList<>();
        String baseDir = PathUtil.outputModuleDir(BizModule.COLLECT);
        String midDir = PathUtil.moduleDirs().getCollect().get("dir") + "/normal";
        File file = new File(baseDir, midDir);
        List<String> resList = new ArrayList<>();
        try {
            file.mkdirs();
            for (MultipartFile multipartFile : files) {
                String filename = multipartFile.getOriginalFilename();
                LambdaQueryWrapper<NormalFilePO> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(NormalFilePO::getName,filename);
                long count = count(queryWrapper);
                if (count >0) {
                    log.info("文件重复上传,不处理:{}",filename);
                    resList.add(filename);
                    continue;
                }
                File path = new File(file, filename);
                multipartFile.transferTo(path);
                NormalFilePO po = new NormalFilePO();
                po.setUploadDate(now);
                po.setName(filename);
                po.setType(dataType);
                po.setPath(midDir);
                po.setSize(path.length());
                list.add(po);

            }
        } catch (Exception e) {
            log.error("上传异常",e);
            throw new ServiceException("上传异常");
        }
        saveBatch(list);
        return resList;
    }

    @Override
    public boolean delFile(Long id) {
        NormalFilePO byId = getById(id);
        String baseDir = PathUtil.outputModuleDir(BizModule.COLLECT);
        File file = new File(baseDir, byId.getPath());
        File target = new File(file, byId.getName());
        removeById(id);
        target.delete();
        return true;
    }

    @Override
    public boolean delBatch(List<Long> delParam) {
        List<NormalFilePO> normalFilePOS = listByIds(delParam);
        String baseDir = PathUtil.outputModuleDir(BizModule.COLLECT);
        if (CollectionUtil.isNotEmpty(normalFilePOS)) {
            for (NormalFilePO normalFilePO : normalFilePOS) {
                File file = new File(baseDir, normalFilePO.getPath());
                File target = new File(file, normalFilePO.getName());
                target.delete();
            }
        }
        removeBatchByIds(delParam);
        return true;
    }

    @Override
    public String preview(Long id) {
        return download(id);
    }

    @Override
    public String download(Long id) {
        NormalFilePO byId = getById(id);
        if (null != byId) {
            File file = new File(PathUtil.outputModuleDir(BizModule.COLLECT) + byId.getPath(), byId.getName());
            return file.getAbsolutePath();
        }else {
            return null;
        }
    }

    @Override
    public String downloadBatch(List<Long> ids) {
        List<NormalFilePO> list = listByIds(ids);
        String baseDir = PathUtil.outputModuleDir(BizModule.COLLECT);
        String url = PathUtil.tmpModuleDir(BizModule.COLLECT)+ "/"+ DateUtil.format(new Date(),"yyyyMMddHHmmss")+".zip";
        if (CollectionUtil.isNotEmpty(list)) {
            File[] toZipArr = new File[list.size()];
            for (int i = 0; i < list.size(); i++) {
                toZipArr[i] = new File(baseDir+list.get(i).getPath(),list.get(i).getName());
            }
            File zip = ZipUtil.zip(new File(url), false, toZipArr);
            url = zip.getAbsolutePath();
        }
        return url;
    }
}
